<?php

namespace App\Http\Controllers\Kms\App\Attendance;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Kms\Attendance\AttendanceValidate;
use App\Service\BaseService;
use App\Service\Kms\Attendance\AttendanceService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class AttendanceController extends BaseController
{
    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function dailyPointTraceUpload(Request $request): JsonResponse
    {
        $params = AttendanceValidate::dailyPointTraceUploadValidate($request->all());
        AttendanceService::dailyPointTraceUpload($params);
        return $this->success();
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function fieldTrace(Request $request): JsonResponse
    {
        $nowUid = $request->user()->rmsUserId;
        $uid    = (int)$request->get('uid', 0);
        if ($uid) {// 判断当前用户是否有权限查看别人的轨迹
            $data = AttendanceService::attendanceUserCheck($nowUid);
            if (!$data['isCheck']) {
                return BaseService::throwErr("暂无权限查看");
            }
        } else {
            $uid = $nowUid;
        }
        $params = AttendanceValidate::fieldTraceListValidate(
            $request->merge(["uid" => $uid])->all()
        );
        return $this->success(AttendanceService::fieldTraceV3($params));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException|GuzzleException
     */
    public function punchShare(Request $request): JsonResponse
    {
        $params = AttendanceValidate::punchShareValidate($request->all());
        AttendanceService::punchShare($params);
        return $this->success();
    }

    /**
     * 获取考勤用户查看权限
     * @param Request $request
     * @return JsonResponse
     */
    public function attendanceUserCheck(Request $request): JsonResponse
    {
        $uid = request()->user()->rmsUserId;
        return $this->success(AttendanceService::attendanceUserCheck($uid));
    }

    /**
     * 获取考勤用户
     * @param Request $request
     * @return JsonResponse
     */
    public function attendanceUser(Request $request): JsonResponse
    {
        $uid  = request()->user()->rmsUserId;
        return $this->success(AttendanceService::attendanceUser($uid));
    }
}
